import { z } from "zod";
import { codeartsrepoRequest, buildUrl } from "../common/utils.js";
import { FileContentSchema } from "../common/types.js";

// 查询某个仓库的文件信息
export const ListFilesByQuerySchema = z.object({
  project_id: z.string().describe("项目ID"),
  repo_id: z.string().describe("仓库ID"),
  path: z.string().describe("文件路径"),
  ref: z.string().optional().describe("引用（分支名、标签名或提交ID）"),
});

// 功能实现
export async function listFilesByQuery(
  projectId: string,
  repoId: string,
  path: string,
  ref?: string
) {
  const url = buildUrl(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/files`, {
    path,
    ref
  });

  const response = await codeartsrepoRequest(url);
  
  // 根据路径是目录还是文件进行不同的解析
  try {
    // 尝试作为文件数组解析（目录内容）
    return z.array(FileContentSchema).parse(response);
  } catch (error) {
    // 如果上面解析失败，尝试作为单个文件解析
    return FileContentSchema.parse(response);
  }
}

// 获取单个文件内容
export async function getFileContent(
  projectId: string,
  repoId: string,
  path: string,
  ref?: string
) {
  const url = buildUrl(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/files/raw`, {
    path,
    ref
  });

  const response = await codeartsrepoRequest(url);
  return response as string;
}

// 创建或更新文件
export async function createOrUpdateFile(
  projectId: string,
  repoId: string,
  path: string,
  content: string,
  commitMessage: string,
  branch: string
) {
  const response = await codeartsrepoRequest(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/files`, {
    method: "POST",
    body: {
      path,
      content, // Base64编码的内容
      commit_message: commitMessage,
      branch
    }
  });
  
  return FileContentSchema.parse(response);
}

// 删除文件
export async function deleteFile(
  projectId: string,
  repoId: string,
  path: string,
  commitMessage: string,
  branch: string
) {
  await codeartsrepoRequest(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/files`, {
    method: "DELETE",
    body: {
      path,
      commit_message: commitMessage,
      branch
    }
  });
  
  return { success: true };
} 